import os

from M3uGenTools.M3uGenTools import M3uGenTools


def main():
    with open('source/cucn_source.m3u8', 'r', encoding="utf-8") as f:
        name = []
        url = []
        for line in f:
            if line.startswith('#EXTINF:-1'):
                channel_name = line.split(',')[-1].strip()
                name.append(channel_name)
            elif line.startswith('http'):
                channel_url = line.strip()
                url.append(channel_url)
            else:
                continue
    blacklist = ['购物', '房产', '广东移动', '汽摩', '靓装', 'CETV早期教育',
                 '武术世界', 'IPTV', 'CCTV中学生', '国学频道', '环球奇观',
                 '梨园频道', '现代教育']
    if len(name) == len(url):
        channel_base_info = []
        for i in range(len(name)):
            if '广东珠江' in name[i]:
                cname = name[i].replace('广东珠江', '珠江频道')
            else:
                cname = name[i]
            if not match_channel_name(cname, blacklist=blacklist):
                channel_base_info.append({"name": cname,
                                          "url": url[i]
                                          })
        channel_info = M3uGenTools(channel_base_info,
                                   channel_logo_json_path='.' + os.sep + 'logo' + os.sep + 'logo.json')
        if os.path.exists('/www'):
            output = '/www' + os.sep + 'allinone.m3u'
            channel_info.write_m3u(m3u_path=output)
        channel_info.write_m3u()


def match_channel_name(name, blacklist):
    for i in blacklist:
        if i in name:
            return True


if __name__ == '__main__':
    main()
